package by.grsu.mikhailava.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.mikhailava.entity.Answer;
import by.grsu.mikhailava.table.AnswerTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class AnswerDao extends AbstractDao<AnswerTable, Answer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9088443610849438215L;

	public AnswerDao(String rootFolderPath) {
		super(rootFolderPath);}
		
		@Override
		public void saveNew(Answer newAnswer) {
			newAnswer.setId(getNextId());
			final AnswerTable answerTable = deserializeFromXml();
			answerTable.getRows().add(newAnswer);
			serializeToXml(answerTable);

		}


		@Override
		public void update(Answer entity) {
			final AnswerTable answerTable = deserializeFromXml();
			for (Answer a : answerTable.getRows()) {
				if (a.getId().equals(entity.getId())) {
					a.setAnswerName(entity.getAnswerName());
					a.setQuestionId(entity.getQuestionId());
					a.setAnswerRole(entity.getAnswerRole());
				}
			}
			serializeToXml(answerTable);
		}

		@Override
		public Answer get(Serializable id) {
			final AnswerTable answerTable = deserializeFromXml();
			for (Answer a : answerTable.getRows()) {
				if (a.getId().equals(id)) {
					return a;
				}
			}
			return null;
		}

		public List<Answer> getByAnswerID(Serializable id) {
			final AnswerTable answerTable = deserializeFromXml();
			List<Answer> answer = new ArrayList<Answer>();
			for (Answer a : answerTable.getRows()) {
				if (a.getQuestionId().equals(id)) {
					answer.add(a);
				}
			}
			return answer;
		}

		public List<Answer> getByQuestionID(Serializable id) {
			final AnswerTable answerTable = deserializeFromXml();
			List<Answer> answer = new ArrayList<Answer>();
			for (Answer a : answerTable.getRows()) {
				if (a.getQuestionId()!=null) {
					if (a.getQuestionId().equals(id)) {
						answer.add(a);
					}
				}
			}
			return answer;
		}

		@Override
		public List<Answer> getAll() {
			AnswerTable answerTable = deserializeFromXml();
			return answerTable.getRows();
		}

		@Override
		public void delete(Serializable id) {
			final AnswerTable answerTable = deserializeFromXml();
			Answer answerToDelete = null;
			for (Answer a : answerTable.getRows()) {
				if (a.getId().equals(id)) {
					answerToDelete = a;
				}
			}
			answerTable.getRows().remove(answerToDelete);
			serializeToXml(answerTable);
		}

		@Override
		protected Class<AnswerTable> getTableClass() {
			return AnswerTable.class;
		}

	
	

}
